package com.hzw.net.executor

import android.os.Handler
import android.os.Looper
import java.util.concurrent.Executor
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

/**
 * 各种线程池集中管理调用
 */
object AppExecutor {

    private val cachedThreadPool: ExecutorService = Executors.newCachedThreadPool()
    private val ioThreadPool: ExecutorService = Executors.newFixedThreadPool(5)
    private val singleThreadPool: ExecutorService = Executors.newSingleThreadExecutor()
    private val mainThreadExecutor: MainThreadExecutor = MainThreadExecutor()

    fun mainThread(block: () -> Unit) {
        mainThreadExecutor.execute(block)
    }

    fun delayed(duration: Long, block: () -> Unit) {
        mainThreadExecutor.handler.postDelayed(block, duration)
    }

    fun singleThread(block: () -> Unit) {
        singleThreadPool.submit(block)
    }

    fun singleThread(runnable: Runnable) {
        singleThreadPool.submit(runnable)
    }

    fun ioThread(block: () -> Unit) {
        ioThreadPool.execute(block)
    }

    fun cachedThread(block: () -> Unit) {
        cachedThreadPool.execute(block)
    }

    class MainThreadExecutor : Executor {
        val handler = Handler(Looper.getMainLooper())
        override fun execute(command: Runnable) {
            handler.post(command)
        }
    }
}